package com.api.controller;

import com.api.annotation.ApiAnnotation;
import com.api.cache.CacheTemplate;
import com.api.constant.CommonConstant;
import com.api.interceptor.ApiInterceptor;
import com.api.model.TUser;
import com.api.service.UserService;
import com.api.utils.JsonReturnUtils;
import com.api.utils.StringUtils;
import com.api.utils.TokenCacheUtils;
import com.api.utils.VerificationUtil;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by PC on 2017/7/4.
 */
@RestController
@RequestMapping("api/user")
public class UserController {
    private static final Logger logger = Logger.getLogger(UserController.class);
    private static final String Code = "6666";
    private UserService userService;
    private static final Double Wallet = 0.0;
    private CacheTemplate cacheTemplate;

    @RequestMapping(value = "login")
    public Object login(String loginName, String password) {
        if (StringUtils.isBlank(loginName) || !VerificationUtil.isMobile(loginName)) {
            return JsonReturnUtils.fail("A001");
        }
        if (!Code.equals(password)) {
            return JsonReturnUtils.fail("A002");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("mobile", loginName);
        params.put("status", CommonConstant.DataStatus.Normal.getValue());
        TUser user = (TUser) userService.selectOneByParams(params);
        if (user == null) {
            user = new TUser();
            user.setMobile(loginName);
            user.setName(userService.getName());
            user.setStatus(CommonConstant.DataStatus.Normal.getValue());
            user.setPassword(userService.getPassword());
            user.setFace(userService.getFace());
            user.setWallet(Wallet);
            user.setCreateTime(System.currentTimeMillis());
            user.setUpTime(System.currentTimeMillis());
            userService.insertSelective(user);
        }
        String token = TokenCacheUtils.setToken(cacheTemplate, user.getId());
        Map<String, Object> json = JsonReturnUtils.success(user);
        json.put("token", token);
        return json;
    }

    @ApiAnnotation
    @RequestMapping(value = "logout")
    public Object logout() {
        TUser user = ApiInterceptor.getUserByRequest();
        if (user != null) {
            TokenCacheUtils.logout(cacheTemplate, user.getId());
        }
        return JsonReturnUtils.success();
    }

    @ApiAnnotation
    @RequestMapping(value = "info")
    public Object info() {
        TUser user = ApiInterceptor.getUserByRequest();
        user.setPassword("");
        return JsonReturnUtils.success(user);
    }
}
